import csv
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from exts import db
from models import Departments, Employees, DeptEmp, DeptManager, DeptManagerTitle, Titles  # noqa

import config


def insert_csv(session, path, model):
    print(f"开始注入{path}")
    with open(path, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        data = [row for row in reader]
    session.bulk_insert_mappings(model, data)
    session.commit()
    print(f"{path}注入成功")


def insert_all():
    engine = create_engine(config.BaseConfig.DATABASE_URI)
    db.metadata.create_all(engine)
    session = sessionmaker(bind=engine)()

    insert_csv(session, '../departments.csv', Departments)
    insert_csv(session, '../employees.csv', Employees)
    insert_csv(session, '../dept_emp.csv', DeptEmp)
    insert_csv(session, '../dept_manager.csv', DeptManager)
    insert_csv(session, '../titles.csv', Titles)
